import { createRouter, createWebHashHistory } from 'vue-router'
import { useAppStore } from '@/store/index'

import Layout from '@/layout/index.vue'

import Home from '@/views/home/index.vue'
import Login from '@/views/login/index.vue'

// 扩展路由meta类型
declare module 'vue-router' {
  interface RouteMeta {
    title?: string
    navLeftShow?: 'logo' | 'back'
    navRightShow?: 'home' | 'back' | 'query' | 'none' | 'collect'
    requiresAuth?: boolean
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: '/',
      component: Layout,
      meta: {
        requiresAuth: true,
      },
      children: [
        {
          path: '/',
          component: Home,
          meta: {
            title: '首页',
            navLeftShow: 'logo',
            navRightShow: 'home',
            requiresAuth: true
          }
        },
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const appStore = useAppStore()
  const isLoggedIn = appStore.isLogin()
  
  // 如果目标路由需要认证
  if (to.meta.requiresAuth) {
    if (isLoggedIn) {
      // 已登录，允许访问
      next()
    } else {
      // 未登录，重定向到登录页
      next('/login')
    }
  } else {
    // 如果是登录页面且已经登录，重定向到首页
    if (to.path === '/login' && isLoggedIn) {
      next('/')
    } else {
      // 其他情况正常跳转
      next()
    }
  }
})

// 路由后置守卫 - 设置导航栏状态
router.afterEach((to) => {
  const appStore = useAppStore()
  
  // 根据路由meta配置设置导航栏状态
  if (to.meta) {
    // 设置左侧显示状态
    if (to.meta.navLeftShow) {
      appStore.navbar.leftShow = to.meta.navLeftShow
    }
    
    // 设置右侧显示状态
    if (to.meta.navRightShow) {
      appStore.navbar.rightShow = to.meta.navRightShow
    }
    
    // 设置标题
    if (to.meta.title) {
      appStore.setNavTitle(to.meta.title)
    }
  }
})

export default router